<template>
	<view style="position: relative;">
		<my-navbar leftText="我 要 加 入" leftIcon="arrow-left" :custom="false" bgColor="#ffffff" :autoBack="true"
					leftIconSize="40" />
		<view class="container">
			<view>
				<view>
					<u--text :bold="true" size="26" color="#c2c2c2" text="预约主题" /><text>{{venueDetailMsg.eventtitle}}</text>
				</view>
			</view>
			<view>
				<view>
					<u--text :bold="true" size="26" color="#c2c2c2" text="预约地点" /><text>{{venueDetailMsg.detailedaddress}}</text>
				</view>
			</view>
			
			<u-divider></u-divider>
			<view style="margin-top: 40rpx;">
				<u--text :bold="false" size="26" color="#c2c2c2" text="场次时间" />
				<view style="margin: 0 auto;text-align: center; width: 100%;margin-top: 20rpx;">
					<image :src="venueDetailMsg.bigImageList[0].imageurl"></image>
					<!-- <image src="/static/order/time.png"></image> -->
				</view>
				<view style="margin: auto 40rpx;">
					<u-button color="#35a5ed" size="large" @click="clickButton">
						<u-icon name="calendar" color="#ffffff" size="55" label="选择场次时间" :bold="false" labelSize="36"
							labelColor="#ffffff" labelPos="right"></u-icon>
					</u-button>
				</view>
			</view>
		</view>
		<view class="ont-toke" style="margin: auto 40rpx;margin-top: 20rpx;">
			<u--text :bold="false" size="24" color="#353535" align="center" :text='oneToke' />
		</view>
		<my-tabbar></my-tabbar>



		<view style="max-height: 300rpx;">
			<my-action-sheet :list="storeList" :show="showStore" @closeShow="closeShowStore()"></my-action-sheet>
		</view>


		<view>
			<u-popup :show="showTime" @close="close" round="40">
				<view style="margin: 20rpx;">
					<view style="margin: 20rpx auto;">
						<u--text :bold="true" size="34" align="center" text="选择开始时间"></u--text>
					</view>
					<view>
						<u-tabs :current="current" :list="dayList" @click="tabsClick" lineWidth="140rpx"
							lineHeight="4rpx" :activeStyle="activeStyle" :itemStyle="itemStyle" scrollable="ture"
							:inactiveStyle="inactiveStyle" :showSlider="true" sliderWidth="140rpx" gutter="20rpx"></u-tabs>
						<scroll-view scroll-y="true"
							style="max-height: 600rpx;border-top: 2rpx solid #d5d5d5;border-bottom: 2rpx solid #d5d5d5;">
							<u-cell-group>
								<!-- <view v-if="current"> -->
								<!-- <u-cell v-for="(list,indexList) in timeList" :key="indexList"> -->
								<view class="time-item" v-for="(array,indexArray) in timeList" :key="indexArray">
									<view slot="title" class="time">
											<u-tag size="large" :text="array.time" borderColor="#ffffff" shape="circle"
												:plain="array.checked" color="#000000" type="primary" :name="indexArray"
												@click="radioClick(array)">
											</u-tag>
									</view>
								</view>
								<!-- </u-cell> -->
							</u-cell-group>
						</scroll-view>
						<view style="width: 100%;margin: 40rpx auto;">
							<view style="text-align: center;">
								<span style="font-size: 28rpx; color: #555555;">已选时间：</span>
								<span style="font-size: 34rpx; color: #35a5ed;">{{orderDay}} {{orderTime}}</span>
							</view>
							<view style="margin-top: 40rpx;">
								<u-button text="确 认" type="primary" size="large" @click="toSeat"></u-button>
							</view>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import {
		addattendevent  
	} from '@/config/api.js';
	import {
		mapState,
	} from 'vuex'
	export default {
		data() {
			return {
				userinfo:{},
				token:'',
				venueDetailMsg:{},
				
				time: '08:00-23:00',
				showStore: false,
				showTime: false,
				inactiveStyle: {
					fontSize: '30rpx'
				},
				itemStyle: {
					textAlign: 'center',
					width: '140rpx',
					paddingBottom: ' 20rpx',
					lineHeight: '50rpx'
				},
				activeStyle: {
					color: '#35a5ed',
					fontWeight: 'bold'
				},
				dayList: [
				],
				timeList: [
				],
				allTimeList: [],
				orderTime: '',
				orderDay: '',
				orderTimestamp: '',
				current: 0
			}
		},
		methods: {
			convertDateRange() {
			      // 1. 分割时间字符串为开始和结束日期
			     console.log(this.venueDetailMsg.starttime);
				 console.log(this.venueDetailMsg.endtime);
			      // 2. 解析为Date对象
			      const startDate = this.parseDate(this.venueDetailMsg.starttime);
			      const endDate = this.parseDate(this.venueDetailMsg.endtime);
			      console.log(startDate);
				  console.log(endDate);
			      // 3. 生成日期数组
			      this.dayList = this.getDateArray(startDate, endDate);
				  console.log(this.dayList)
			    },
			    
			    // 解析YYYYMMDD格式的字符串为Date对象
			    parseDate(dateStr) {
			      const year = parseInt(dateStr.substring(0, 4));
				  console.log(year);
			      const month = parseInt(dateStr.substring(5, 7)) - 1; // 月份从0开始
				  console.log(month);
			      const day = parseInt(dateStr.substring(8, 10));
				  console.log(day);
			      return new Date(year, month, day);
			    },
			    
			    // 生成从开始日期到结束日期的所有日期数组
			    getDateArray(start, end) {
			      const dateArray = [];
			      const currentDate = new Date(start);
			      
			      // 循环添加每一天，直到超过结束日期
			      while (currentDate <= end) {
			        // 格式化日期为YYYYMMDD
			        const year = currentDate.getFullYear();
			        const month = String(currentDate.getMonth() + 1).padStart(2, '0');
			        const day = String(currentDate.getDate()).padStart(2, '0');
			        const dateStr = `${year}${month}${day}`;
			        
			        dateArray.push({ name: dateStr });
			        
			        // 日期加1天
			        currentDate.setDate(currentDate.getDate() + 1);
			      }
			      
			      return dateArray;
			},
				
			convertTime() {
			      try {
			        // 1. 解析JSON字符串为数组
			        const timeArray = JSON.parse(this.venueDetailMsg.timeperiod);
			        
			        // 2. 映射为带checked属性的对象数组
			        this.timeList = timeArray.map(time => ({
			          time: time,
			          checked: "true"  // 注意：如果需要布尔值则用 true（无引号）
			        }));
			        
			        console.log("转换结果：", this.timeList);
			      } catch (error) {
			        console.error("转换失败：", error);
			        uni.showToast({
			          title: "时间格式解析错误",
			          icon: "none"
			        });
			      }
			},
			
			closeShowTime() {
				this.showTime = false;
			},
			clickButton() {
				this.showTime = true;
				this.orderDay = this.dayList[0].name
				console.log(this.orderDay)
			},
			// 时间标签
			radioClick(array) {
				const that = this
				console.log(array)
				// that.orderTime = array.time
				// array.checked = false
				
				that.timeList.forEach(function(item, key) {
						item.checked = array.time === item.time ? false : true
						if (array.time === item.time) {
							that.orderTime = array.time
						}
				})
	

			},
			
			// tabs 切换
			tabsClick(item) {
				this.current = item.index
				console.log(item, item.timestamp)
				// this.orderDay = uni.$u.date(item.timestamp, 'mm月dd日')
				this.orderDay = item.name
				this.orderTime = ""
			},
			close() {
				this.current = 0
				this.showTime = false
			},
			// 验证字段是否为空
			validateForm() {
			  // 检查活动标题
			  if (this.venueDetailMsg.eventtitle=='') {
				uni.showToast({
				  title: '请输入标题',
				  icon: 'none', // 不显示图标，只显示文字
				  duration: 2000
				});
				return false; // 验证失败
			  }
			  
			  return true;
			},
			toSeat() {
				if (this.orderTime == '') {
					uni.showToast({
						title: "请选择场次时间",
						icon: 'error'
					})
				} else {
					
					// 从本地存储获取登录状态（实际应根据项目登录逻辑，如token、用户信息等判断）
					const isLogin = uni.getStorageSync('isLogin');
					if (!isLogin) {
					  // 显示弹窗，用户必须点击确认才能继续
					  uni.showModal({
					    title: '提示',
					    content: '加入失败，请先登录获取手机号',
					    showCancel: false, // 不显示取消按钮，强制用户确认
					    success: (res) => {
					      if (res.confirm) {
					        // 用户点击确认后跳转
					        uni.switchTab({
					          url: '/pages/mine/mine' // 替换为实际主页路径
					        });
					      }
					    }
					  });
					}  else {
						this.userinfo = JSON.parse(uni.getStorageSync('userInfo'));
						this.token = uni.getStorageSync('token');
						// 先执行验证，若验证失败则不提交
						  if (!this.validateForm()) {
							return; // 直接返回，阻止后续提交逻辑
						  }
						this.toAttend();
						
					}
				}

			},
			async toAttend() {
				
				const {
					data
				} = await addattendevent({
					eventid: this.venueDetailMsg.eventid,
					eventtitle:this.venueDetailMsg.eventtitle,
					imageurl:this.venueDetailMsg.bigImageList[0].imageurl,
					detailedaddress:this.venueDetailMsg.detailedaddress,
					eventcity:this.venueDetailMsg.eventcity,
					orderday:this.orderDay,
					ordertime:this.orderTime,
					phone:this.userinfo.phone,
					nickName:this.userinfo.nickName,
					eventcity:this.userinfo.city,
					openid:this.token
				}, {
					header: {
						'Content-Type': 'application/json'
					},
				})
				console.log(data)
				
				if (data.code == 200) {
					uni.showToast({
						icon: 'success',
						title: '恭喜您报名成功'
					})
					
					// 序列化 + 编码（关键：避免特殊字符截断）
					const jsonStr = encodeURIComponent(JSON.stringify(this.venueDetailMsg));
					uni.navigateTo({
						url: '/other_pages/venueDetail/qrcode?queryObj='+jsonStr
					})
				} else {
					uni.showToast({
						icon: 'success',
						title: '很遗憾,加入失败'
					})
				}
				
				
				setTimeout(() => {
					uni.hideLoading()
				}, 2000)
			},

		},
		computed: {
			...mapState(['oneToke', 'store', 'storeList'])
		},
		onLoad(options) { // options 包含路由传递的所有参数
		    // 1. 接收参数（options.参数名 对应传递时的 key）
			console.log(options.queryObj);
		    const jsonStr = decodeURIComponent(options.queryObj);
		    
		    // 2. 反序列化还原为 JSON 对象
		    this.venueDetailMsg = JSON.parse(jsonStr);
		    
		    // 3. 验证结果（可根据实际需求处理）
		    console.log("接收的 JSON 对象：", this.venueDetailMsg);
			//4.日期数组转换
			this.convertDateRange();
			//5.时间列表转换
			this.convertTime();
			},
		onReady() {},
		onShow() {}
	}
</script>

<style lang="scss">
	.container {
		background-color: #FFFFFF;
		// width: 100%;
		margin: 40rpx;
		padding: 40rpx;
		border-radius: 20rpx;
	}

	.ont-toke {
		// position: absolute;
		// width: 100%;
		// background-color: #4CD964;
		// margin-top: ;
	}

	.time {
		// margin: auto 40rpx;
	
		// margin-left: 40rpx;
		// padding: auto 140rpx;
		margin: 0 auto;  /* 让时间容器在父元素中水平居中 */
		text-align: center;  /* 让内部标签整体居中排列 */
		padding: 0 30%;

		.time-item {
			display: inline-block;
			margin: 20rpx auto;
			font-size: 34rpx;
		}
	}
</style>
